package com.own.component.springdoc;

import com.own.component.autoconfig.property.token.TokenProperty;
import com.own.component.springdoc.base.BaseSpringDocConfiguration;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.GroupedOpenApi;
import org.springdoc.core.customizers.OperationCustomizer;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;


/**
 * DefaultSecuritySpringDocConfiguration
 *
 * @author chenxueli
 * @date 2023-12-05 16:42:13
 */
@Slf4j
@SpringBootConfiguration
public class DefaultSecuritySpringDocConfiguration extends BaseSpringDocConfiguration {

    @Resource
    private TokenProperty tokenProperty;

    /**
     * 创建的springdoc信息
     *
     * @param groupName      分组名称
     * @param packagesToScan 扫描的包
     * @return 分组文档信息
     */
    @Override
    protected GroupedOpenApi defaultCreate(String groupName, String... packagesToScan) {
        return GroupedOpenApi.builder()
                .group(groupName)
                .addOperationCustomizer(operationCustomizer())
                .packagesToScan(packagesToScan)
                .build();
    }

    @Bean
    public OperationCustomizer operationCustomizer() {
        return (operation, handlerMethod) -> {
            // 如果存在LoginIgnore注解，则不添加token参数
//            if (!handlerMethod.hasMethodAnnotation(LoginIgnore.class)) {
//                return operation.addParametersItem(buildTokenParameter());
//            }
            return operation;
        };
    }

    private Parameter buildTokenParameter() {
        return new Parameter()
                .in(ParameterIn.HEADER.toString())
                .name(tokenProperty.getTokenRequestField())
                .description(tokenProperty.getTokenRequestField())
                .schema(new StringSchema())
                .required(false);
    }

}
